package com.hll.javaee.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class Download extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 以这种方式获取resources/1.txt
    // class.getResource(path),如果path以/开头,那么以classes为根目录, 如果是没有的,则以当前class文件所在文件夹为根目录
    // classLoader.getResource(path),path不能带/开头,默认以classes目录为根
    // 底层原理自己搜博客
    String path =
        this.getClass().getClassLoader().getResource("1.txt").getPath().replace("\\\\", "/");
    String fileName = path.substring(path.lastIndexOf("/") + 1); // 文件名
    FileInputStream in = new FileInputStream(path);

    // 设置消息头,表示下载给用户,而不是直接显示,直接显示的话，改成 atttchment:filename
    response.setHeader(
        "Content-Disposition",
        "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 文件名乱码

    ServletOutputStream out = response.getOutputStream();

    // 输出
    int len = 0;
    byte[] bytes = new byte[1024];
    while ((len = in.read(bytes)) != -1) {
      out.write(bytes, 0, len);
    }
    in.close();
    out.close();
  }
}
